﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoreVirtuoso.Config;
using CoreVirtuoso.Descriptions;
using VirtuosoDal.Config;
using VirtuosoDal.Entities;
using VirtuosoDal.Repositories.RdfRepositories.GeoNames;
using VirtuosoDal.Repositories.RdfRepositories.Lgd;

namespace CoreVirtuoso.Helpers
{
   internal static class EventExtraFillingHelper
   {
      public static void FillGeoNamesValuesForEvents(IEnumerable<Event> events,
         string language)
      {
         Dictionary<string, Event> cityUriToEventMappings;
         List<string> geoObjectsUris;
         InitializeValuesFilling(events, e => e.CityUri, out cityUriToEventMappings, out geoObjectsUris);

         GeoNamesRepository geoNamesRepository = new GeoNamesRepository();
         List<GeoNamesCityShortDescription> citiesDescriptions =
            geoNamesRepository.GetGeoNamesShortCitiesDescriptions(geoObjectsUris, language);

         foreach (var cityDescription in citiesDescriptions)
         {
            var @event = cityUriToEventMappings[cityDescription.Uri];

            @event.CityName = cityDescription.Name;
            @event.CountryName = cityDescription.CountryName;
         }
      }

      public static void FillLgdValuesForEvents(IEnumerable<Event> events)
      {
         Dictionary<string, Event> placeToEventMappings;
         List<string> geoObjectsUris;
         InitializeValuesFilling(events, e => e.PlaceUri, out placeToEventMappings, out geoObjectsUris);

         LgdContentRepository lgdContentRepository = new LgdContentRepository();
         List<ObjectDescription> objectsDescriptions = lgdContentRepository.GetLgdObjectsDescriptions(geoObjectsUris);

         foreach (var objectDescription in objectsDescriptions)
         {
            var @event = placeToEventMappings[objectDescription.Uri];

            @event.PlaceName = objectDescription.Name;
         }
      }

      private static void InitializeValuesFilling(IEnumerable<Event> events,
                                                   Func<Event, string> propertyFunc,
                                                   out Dictionary<string, Event> uriToEventMappings,
                                                   out List<string> uris)
      {
         uriToEventMappings = new Dictionary<string, Event>();
         uris = new List<string>();

         foreach (var @event in events)
         {
            var uri = propertyFunc(@event);
            if (uri != null)
            {
               uriToEventMappings[uri] = @event;
               uris.Add(uri);
            }
         }
      }
   }
}